package cn.itzd.service.impl;

import cn.itzd.entity.LoginUser;
import cn.itzd.mapper.SysUserMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: dada
 * @Version: 1.0
 * @Description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名查询用户信息
        if (StringUtils.isEmpty(username)){
            throw new UsernameNotFoundException("用户名未填写");
        }
        LoginUser longinUser = userMapper.queryUserByUserName(username);
        if (ObjectUtils.isEmpty(longinUser)) {
            throw new RuntimeException("用户不存在！");
        }
        //角色
        longinUser.setAuthor(power(longinUser.getId()));
        return longinUser;
    }

    /**
     * 获取角色
     * @param id
     * @return
     */
    private String[] power(Long id) {
        //通过用户id查询权限信息
        List<String> powers =  userMapper.getPower(id);
        return powers.stream().toArray(String[]::new);
    }
}
